<script>
import Treeselect from "@riophae/vue-treeselect";
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {api} from "@/assets/static/js/settings";

function objectToFormData(obj) {
  if (typeof obj.avatar !== 'object') {
    // 如果传的不是文件对象，代表着是原来的图片
    delete obj.avatar
  }
  let formData = new FormData();
  Object.keys(obj).forEach(property => {
    if (Array.isArray(obj[property])) {
      // 如果是数组需要处理一下数据
      obj[property].forEach(item => {
        formData.append(property, item)
      })
    } else {
      formData.append(property, obj[property])
    }
  })
  return formData;
}

export default {
  name: "UserInfoView",
  components: {Treeselect},
  data() {
    return {
      uploadUrl: '',
      editForm: {},
      schoolData: [],
// 所有部门列表
      deptData: [],
      // 所有角色数据
      roleForm: {},
      roleTreeData: [],
      // 表单规则
      editFormRules: {
        username: [
          {required: true, message: '请输入用户名称', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'}
        ],
        is_show: [
          {required: true, message: '请选择状态', trigger: 'blur'}
        ],
        school: [
          {required: true, message: '请选择学校', trigger: 'blur'}
        ]
      },
      // 选择角色时 多选数据
      multipleSelection: [],
      treeCheckedKeys: [],
      checkStrictly: true,
    }
  },
  methods: {
    // 提交表单动作
    onSubmit() {
      this.$refs.editForm.validate((valid) => {
        // 表单验证通过，进行提交操作
        if (valid) {
          let formData = objectToFormData(this.editForm)
          this.$axios.put(api.info + this.$cookies.get('userInfo').id + '/', formData, {
            headers: {
              'content-type': 'multipart/form-data'
            }
          }).then(res => {
                if (res) {
                  this.$message({
                    showClose: true,
                    message: '恭喜你，操作成功',
                    type: 'success',
                    onClose: () => {
                      this.getUserList()
                    }
                  })
                }
              }
          )
        } else {
          // 表单验证未通过
          console.log('Form validation failed');
          return false;
        }
      })
    },
    handleAvatar(file) {
      let avatar = new FileReader()
      avatar.readAsDataURL(file)
      avatar.onload = () => {
        this.$set(this.editForm, 'avatar', file)
        this.uploadUrl = avatar.result
        // console.log(this.editForm.avatar)
      }
      // 阻止上传
      return false
    },
    // vue-treeselect 配置label字段和children字段
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.menus
      }
    },
// 处理多选数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.delBtlStatu = val.length === 0
    },
    getUserList() {
      let user = this.$cookies.get('userInfo')
      this.$axios.get(api.info + user.id + '/').then(res => {
        if (res) {
          this.editForm = res.results
        }
      })
    }
  },
  created() {
    this.getUserList()
    // 获取所有角色
    this.$axios.get(api.role).then(res => {
      if (res) {
        this.roleTreeData = res.results
      }
    })
    // 获取所有部门
    this.$axios.get(api.position_list).then(res => {
      if (res) {
        this.deptData = res.results
      }
    })
    // 获取所有学校
    this.$axios.get(api.school).then(res => {
      if (res) {
        this.schoolData = res.results
      }
    })
  }

}
</script>

<template>
  <div class="block">
    <el-form ref="editForm" :model="editForm" :rules="editFormRules" size="small" label-width="80px">
      <el-form-item label="用户名:" prop="username">
        <el-input v-model="editForm.username"/>
      </el-form-item>
      <el-form-item label="新密码:" prop="password">
        <el-input v-model="editForm.password"/>
      </el-form-item>
      <el-form-item label="电话:" prop="phone">
        <el-input v-model.number="editForm.phone"/>
      </el-form-item>
      <el-form-item label="昵称:" prop="nickName">
        <el-input v-model="editForm.nick_name"/>
      </el-form-item>
      <el-form-item label="邮箱:" prop="email">
        <el-input v-model="editForm.email"/>
      </el-form-item>
      <el-form-item label="部门:" prop="position">
        <treeselect
            style="width: 170px"
            placeholder="选择部门"
            v-model="editForm.position"
            :options="deptData"
            :normalizer="normalizer"
        />
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="editForm.gender" style="width: 178px">
          <template class="radio-group">
            <el-radio :label="1" border>男</el-radio>
            <el-radio :label="0" border>女</el-radio>
            <el-radio :label="2" border>保密</el-radio>
          </template>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态:" prop="is_show">
        <el-radio-group v-model="editForm.is_show">
          <el-radio :label="false" border>禁用</el-radio>
          <el-radio :label="true" border>启用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item style="margin-bottom: 0;" label="角色:" prop="roles">
        <el-select
            v-model="editForm.role"
            style="width: 437px"
            multiple
            placeholder="请选择"
        >
          <el-option
              v-for="item in roleTreeData"
              :key="item.name"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="margin-bottom: 0;" label="学校:" prop="school">
        <el-select
            v-model="editForm.school"
            style="width: 437px"
            placeholder="请选择">
          <el-option
              v-for="item in schoolData"
              :key="item.name"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="头像:" prop="avatar">
        <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :before-upload="handleAvatar">
          <img v-if="editForm.avatar" :src="typeof editForm.avatar =='object'?uploadUrl:editForm.avatar"
               class="avatar" alt="图片加载失败">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即修改</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.block {
  margin: 50px;
  width: 85%;
  display: flex;
  justify-content: center;
}

.radio-group {
  display: flex;
  justify-content: space-evenly;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  line-height: 78px;
  text-align: center;
}

.avatar {
  width: 78px;
  height: 78px;
  display: block;
  border-radius: 50%;
}
</style>